﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Kugar.Core.Data;
using Kugar.Core.Data.MSSQLHelper;
using Kugar.Core.ExtMethod;

namespace Kugar.Core.Security.Providers.MSSQL
{
    public class MSSQL_PermissionCheckProvider : PermissionCheckProviderBase
    {
        private static KeyValuePair<int, int>[] _emptyPermissionIDList = new KeyValuePair<int, int>[1] { new KeyValuePair<int, int>(-1, 0) };
        private static KeyValuePair<string, int>[] _emptyPermissionNameList = new KeyValuePair<string, int>[1] { new KeyValuePair<string, int>("All", 0) };

        private Func<SQLDataHelper> _connGetter = null;
        private bool _isAutoDisposeConn = false;

        internal MSSQL_PermissionCheckProvider(Func<SQLDataHelper> connGetter, bool isAutoDisposeConn = false)
        {
            _connGetter = connGetter;


        }

        #region Implementation of IPermissionProvider

        public override int CheckPermissionByID(int userID, int permissionID)
        {
            var conn = getConn();

            try
            {
                return conn.ExecuteProcedureScalar<int>("p_PermissionCheck_GetPermissionByID", false, new[]
                    {
                        new SqlParameter("@userID", userID),
                        new SqlParameter("@PermissionID", permissionID),
                    });
            }
            catch (Exception)
            {
                return 0;
            }
            finally
            {
                if (_isAutoDisposeConn)
                {
                    conn.Dispose();
                }
            }


        }

        public override int CheckPermissionByName(int userID, string permissionName)
        {
            var conn = getConn();

            try
            {
                return conn.ExecuteProcedureScalar<int>("p_PermissionCheck_GetPermissionByName", false, new[]
                        {
                            new SqlParameter("@userID", userID),
                            new SqlParameter("@PermissionName", permissionName),

                        });
            }
            catch (Exception)
            {
                return 0;
            }
            finally
            {
                if (_isAutoDisposeConn)
                {
                    conn.Dispose();
                }
            }



        }

        public override KeyValuePair<int, int>[] CheckPermissionByIDList(int userID, int[] permissionIDList)
        {
            var conn = getConn();

            try
            {
                var tbl = conn.ExecuteProcedureDataTable("p_PermissionCheck_GetPermissionByIDList", false, new[]
                        {
                            new SqlParameter("@userID", userID),
                            new SqlParameter("@PermissionID", permissionIDList.JoinToString(',')),
                        });

                if (!tbl.IsEmptyData())
                {
                    var lst =
                        tbl.AsEnumerable().Select((row) => new KeyValuePair<int, int>(row["PermissionID"].ToInt(),
                                                                                      row["ControlValue"].ToInt()))
                           .ToArray();

                    //var lst = new KeyValuePair<int, int>[tbl.Rows.Count];

                    //for (int i = 0; i < tbl.Rows.Count; i++)
                    //{
                    //    var row = tbl.Rows[i];
                    //    lst[i] = new KeyValuePair<int, int>(row["PermissionID"].ToInt(),row["ControlValue"].ToInt());
                    //}

                    return lst;
                }
                else
                {
                    return _emptyPermissionIDList;
                }
            }
            catch (Exception)
            {
                return _emptyPermissionIDList;
            }
            finally
            {
                if (_isAutoDisposeConn)
                {
                    conn.Dispose();
                }
            }


            //return new KeyValuePair<int, int>[0];
        }

        public override KeyValuePair<string, int>[] CheckPermissionByNameList(int userID, string[] permissionNameList)
        {
            var conn = getConn();

            try
            {
                var tbl = conn.ExecuteProcedureDataTable("p_PermissionCheck_GetPermissionByIDList", false, new[]
                        {
                            new SqlParameter("@userID", userID),
                            new SqlParameter("@PermissionName", permissionNameList.JoinToString(',')),
                        });

                if (!tbl.IsEmptyData())
                {
                    var lst =
                        tbl.AsEnumerable()
                           .Select((row) => new KeyValuePair<string, int>(row["PermissionName"].ToString(),
                                                                          row["ControlValue"].ToInt())).ToArray();

                    //var lst = new KeyValuePair<int, int>[tbl.Rows.Count];

                    //for (int i = 0; i < tbl.Rows.Count; i++)
                    //{
                    //    var row = tbl.Rows[i];
                    //    lst[i] = new KeyValuePair<int, int>(row["PermissionID"].ToInt(),row["ControlValue"].ToInt());
                    //}

                    return lst;
                }
                else
                {
                    return _emptyPermissionNameList;
                }
            }
            catch (Exception)
            {
                return _emptyPermissionNameList;
            }
            finally
            {
                if (_isAutoDisposeConn)
                {
                    conn.Dispose();
                }
            }

        }

        public override RMS_PermissionValueCollection GetPermissionListByUserID(int userID)
        {
            var conn = getConn();

            try
            {
                var cmd = conn.CreateCommand();

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "p_UserPermission_GetPermissionListByID";
                cmd.Parameters.Add(new SqlParameter("@UserID", userID));

                var lst = conn.ExecuteDataEntity<RMS_PermissionItemValue>(cmd, null, null, false);

                if (lst != null)
                {
                    return new RMS_PermissionValueCollection(lst);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (_isAutoDisposeConn)
                {
                    conn.Dispose();
                }
            }

        }



        #endregion

        private SQLDataHelper getConn()
        {
            return _connGetter();
        }

        #region Implementation of IDisposable

        public void Dispose()
        {

        }

        #endregion
    }
}
